package com.example.com.skills_utf8;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.Image;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.VideoView;

import com.app.BaseActivity;
import com.app.MyCamera;
import com.app.MyPhotoAlbum;
import com.app.net.NetHelper;
import com.app.net.NetHelper_File;
import com.app.util.Utils;
import com.app.util.Utils_Data;
import com.app.util.Utils_Image;
import com.app.util.Utils_Log;
import com.app.video.MyVideo;
import com.bean.Talk;
import com.bean.TalkMessage;
import com.bean.TalkMessageDB;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.umeng.message.entity.UMessage;
import com.utils.GsonParse;
import com.utils.g;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class _62_1Activity extends BaseActivity {

    private String TAG = _62_1Activity.class.getSimpleName();

    _62_1Activity activity = this;
    Talk talk ;

    ListView listview ;

    /*
    RadioGroup radiogroup;
    RadioButton bar_imjo;
    RadioButton bar_add ;
    */
    ///*
    CheckBox bar_imjo;
    CheckBox bar_add;
    //*/

    Button btn_bar_send;
    EditText et_bar_input;

    List<TalkMessage> listdata = new ArrayList<TalkMessage>();
    Adapter adapter = new Adapter();


    LinearLayout layout_bar_content;

    // imjo聊天表情页面
    _62_1imjoFragment fragment_imjo ;
    _62_1MoreFragment fragment_more;


    BroadcastReceiver mTalkReceiver;


    int bar_last_id = -1;


    PlaySound playsound = new PlaySound();



    DbUtils db;


    MyCamera mycamera = new MyCamera();
    MyPhotoAlbum myphotoalbum = new MyPhotoAlbum();




    void HandlerMessage(String msg) throws JSONException {

        Log.e(TAG, "接收到信息："+msg);

        JSONObject obj = new JSONObject(msg);
        UMessage message = new UMessage( obj );

        String title = message.title;
        String content = message.text;
        String create_at = message.extra.get("create_at");
        String id_umeng = message.extra.get("id_umeng");
        //String content = message.extra.get("content");


        TalkMessage talkmessage = new TalkMessage();
        TalkMessage.ContentEntity contententity = (TalkMessage.ContentEntity)GsonParse.parse(content, TalkMessage.ContentEntity.class);
        //TalkMessage.Umeng_dataEntity umeng_dataentity = (TalkMessage.Umeng_dataEntity)

        talkmessage.setContent(contententity);

        talkmessage.setTitle(title);
        talkmessage.setCreate_at( Long.valueOf(create_at) );
        talkmessage.setId_umeng(id_umeng);
        talkmessage.setType("1");
        listdata.add(talkmessage);
        adapter.refreshToBottom();




        // 提示信息,在列表的右下方显示有新消息


        // 播放音频
        playsound.OnCreate();
        playsound.playBeepSoundAndVibrate();


        g.Save2DB(ApplicationCustom.getInstance().db, talkmessage);





    }



    class PlaySound
    {

        private static final long VIBRATE_DURATION = 200L;
        private MediaPlayer mediaPlayer;
        private boolean playBeep;
        private static final float BEEP_VOLUME = 0.10f;
        private boolean vibrate = false;


        public void OnCreate(){
            playBeep = true;
            AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
            if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
                playBeep = false;
            }
            initBeepSound();
        }

        private void initBeepSound() {
            if (playBeep && mediaPlayer == null) {
                // The volume on STREAM_SYSTEM is not adjustable, and users found it
                // too loud,
                // so we now play on the music stream.
                setVolumeControlStream(AudioManager.STREAM_MUSIC);
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setOnCompletionListener(beepListener);

                AssetFileDescriptor file = getResources().openRawResourceFd(
                        R.raw.beep);
                try {
                    mediaPlayer.setDataSource(file.getFileDescriptor(),
                            file.getStartOffset(), file.getLength());
                    file.close();
                    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    mediaPlayer = null;
                }

            }
        }


        public void playBeepSoundAndVibrate() {
            if (playBeep && mediaPlayer != null) {
                mediaPlayer.start();
            }
            if (vibrate) {
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_DURATION);
            }
        }

        /**
         * When the beep has finished playing, rewind to queue up another one.
         */
        private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.seekTo(0);
            }
        };

    }





    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.e(TAG, "onNewIntent");


        try {
            String data = intent.getStringExtra("data");
            HandlerMessage(data);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public Integer InitLayout() {
        return R.layout.activity__62_1;
    }

    @Override
    public void InitView() {

        listview = (ListView)findViewById(R.id.listview);

        /*
        radiogroup = (RadioGroup)findViewById(R.id.radiogroup);
        bar_imjo = (RadioButton)findViewById(R.id.bar_imjo);
        bar_add = (RadioButton)findViewById(R.id.bar_add);
        */
        ///*
        bar_imjo = (CheckBox)findViewById(R.id.bar_imjo);
        bar_add = (CheckBox)findViewById(R.id.bar_add);
        //*/
        layout_bar_content = (LinearLayout)findViewById(R.id.layout_bar_content);


        fragment_imjo = new _62_1imjoFragment();
        fragment_more = new _62_1MoreFragment();



        /*
        //--
        _62PushIntentService.setMessageInterface(this);


        //--
        _62PushIntentService.setHandler(handler);

        //--
        mTalkReceiver = new _62BroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction( g.Intent.ACTION_MSG_RECIVE );
        this.registerReceiver(mTalkReceiver, filter);
        */



    }

    void replace(int pos){

        Fragment fragment ;
        if(pos == 0){
            fragment = fragment_imjo;
        }
        else{
            fragment = fragment_more;
        }

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.layout_bar_content, fragment);
        ft.commit();



    }


    class _62BroadcastReceiver extends BroadcastReceiver {

        private String TAG = _62BroadcastReceiver.class.getSimpleName();


        @Override
        public void onReceive(Context context, Intent intent) {


            Log.e(TAG, "onReceive");


            try {
                String data = intent.getStringExtra("data");
                JSONObject obj = new JSONObject(data);


            } catch (JSONException e) {
                e.printStackTrace();
            }


        /*
        String title = data.getString("title");
        String content = data.getString("content");
        String create_at = msg.extra.get("create_at");
        String id_umeng = msg.extra.get("id_umeng");
        Long time = data.getLong(create_at);

        TalkMessage message = new TalkMessage();
        message.setName(title);
        message.setContent(content);
        message.setTime(time);
        message.setId_umeng(id_umeng);
        message.setType("1");


        listdata.add(message);
        adapter.notifyDataSetChanged();
         */


        }


    }





    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(mTalkReceiver != null){
            this.unregisterReceiver(mTalkReceiver);
            mTalkReceiver = null;
        }
    }

    @Override
    public void InitListener() {



        // oncheck -> onclick
        bar_imjo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Utils_Log.e(TAG, "OnClick bar_imjo");


                if(bar_imjo.isChecked()){
                    bar_add.setChecked(false);
                    layout_bar_content.setVisibility(View.VISIBLE);
                }
                else{
                    if(!bar_imjo.isChecked() && !bar_add.isChecked()){
                        layout_bar_content.setVisibility(View.GONE);
                    }

                }

                replace(0);
            }
        });

        bar_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Utils_Log.e(TAG, "OnClick bar_add");

                if(bar_add.isChecked()){
                    bar_imjo.setChecked(false);
                    layout_bar_content.setVisibility(View.VISIBLE);
                }
                else{
                    if(!bar_imjo.isChecked() && !bar_add.isChecked()){
                        layout_bar_content.setVisibility(View.GONE);
                    }

                }


                replace(1);

            }
        });



        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                /*
                //if (view.getId() == R.id.layout_content)
                {
                    TalkMessage talkmessage = (TalkMessage)parent.getItemAtPosition(position);
                    Intent intent = new Intent(activity, _62_1MoreFragmentMapActivity.class);
                    intent.putExtra("data", talkmessage.getContent());
                    startActivity(intent);

                }
                */

            }
        });


    }

    @Override
    public void InitProcess() {

        db = ApplicationCustom.getInstance().db;

        String bean = getIntent().getStringExtra("bean");
        talk = (Talk) GsonParse.parse(bean, Talk.class);


        btn_bar_send = (Button)findViewById(R.id.btn_bar_send);
        et_bar_input = (EditText)findViewById(R.id.et_bar_input);


        btn_bar_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 如果能读取通话记录，读出拨打着就能得到用户的手机号码
                String bar_input_str = et_bar_input.getText().toString();
                if (bar_input_str.isEmpty() == false) {
                    //String time = Utils.getNowTime();
                    requestNetDate_sendmessage(talk.getId_umeng(), talk.getId_user(), bar_input_str, "text");
                } else {

                }

            }
        });


        listview.setAdapter(adapter);



    ///*
        //db = DbUtils.create(this, G.PATH_DB, "database.db");
        //db = DbUtils.create(this);
        try {

            List<TalkMessageDB> talkmessage_last = db.findAll(Selector.from(TalkMessageDB.class).where("id_device" ,"=", talk.getId_umeng()));
            if(talkmessage_last != null){

                for(int i =0; i<talkmessage_last.size(); i++){
                    TalkMessageDB messagedb = talkmessage_last.get(i);
                    TalkMessage tm = (TalkMessage)GsonParse.parse(messagedb.getContent(), TalkMessage.class);
                    listdata.add(tm);
                }

                adapter.refreshToBottom();
            }

            // 打印日志
            for(int i =0; i<listdata.size(); i++){
                TalkMessage message = listdata.get(i);
                Utils_Log.e(TAG, message.toString());
            }




        } catch (DbException e) {
            e.printStackTrace();
        }
    //*/

        // 创建数据库
        /*
        DatabaseHelper db = DatabaseHelper.getInstance(activity);
        _62DB_Message.createTable(db.getWritableDatabase());

        _62DB_Message.Bean bean_message = new _62DB_Message.Bean();
        bean_message.setContent("123456");
        bean_message.setMd5(AbMd5.MD5("123456"));
        _62DB_Message.SaveBaseMessageToDb(getContentResolver(), bean_message);
        */


        /*
        try {
            Talk talk1 = new Talk();
            talk1.setId_user("id_user");
            talk1.setId_umeng("id_umeng");
            db.save(talk1);

            Talk talk2 = new Talk();
            talk2.setId_user("id_user2");
            db.save(talk2);

            List<Talk> children = db.findAll(Selector.from(Talk.class));

            System.out.println();

        } catch (DbException e) {
            e.printStackTrace();
        }
        */



    }




    public void update(int i){

        EditText et = et_bar_input;
        String text_old = et.getText().toString();
    //    text += g.imjo_find(i);

        String text = g.imjo_find(i);

        Drawable drawable = getResources().getDrawable(i);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        //需要处理的文本，[smile]是需要被替代的文本
        SpannableString spannable = new SpannableString( text );
        //要让图片替代指定的文字就要用ImageSpan
        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
        spannable.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        et.append(spannable);
        et.setSelection(et.length());


    }


    void requestNetDate_sendmessage(final String id_umeng, final String title, final String content, final String input_type){

        Utils.showLoadingDialog(activity,"",false);

        new NetHelper(activity) {

            @Override
            public String init(ArrayList<BasicNameValuePair> arrayList) {

                String sign = g.token + g.id_umeng;

                arrayList.add(new BasicNameValuePair("id_umeng_from", g.id_umeng));
                arrayList.add(new BasicNameValuePair("id_umeng", id_umeng));
                arrayList.add(new BasicNameValuePair("title", title));
                arrayList.add(new BasicNameValuePair("content", content));
                arrayList.add(new BasicNameValuePair("input_type", input_type));
                arrayList.add(new BasicNameValuePair("sign", Utils_Data.MD5(sign)));

                return g.SERVER_PAY_HOST + g.SERVER_PAY_API.umeng_message_send;
            }

            @Override
            public void onComplete(String s) throws JSONException {

                //回收解压的内存
                System.gc();

                JSONObject obj = new JSONObject(s);
                JSONObject data = obj.getJSONObject("data");

                if (obj.getInt("result") == 0) {


                    TalkMessage message = (TalkMessage)GsonParse.parse( data.toString() , TalkMessage.class);

                    /*
                    String id_umeng = data.getString("id_umeng");  //
                    String title = data.getString("title");
                    String content = data.getString("content");
                    Long time = data.getLong("create_at");

                    TalkMessage message = new TalkMessage();
                    message.setTitle(title);
                    message.setCreate_at(time);
                    message.setId_umeng(id_umeng);
                    message.setType("0");

                    TalkMessage.ContentEntity entity = (TalkMessage.ContentEntity)GsonParse.parse(content, TalkMessage.ContentEntity.class);
                    message.setContent(entity);
                    */


                    listdata.add(message);
                    adapter.refreshToBottom();

                    /*
                    //JSONObject data = new JSONObject(str).getJSONObject("data");
                    String umeng_data_str = data.getString("umeng_data");
                    JSONObject umeng_data = new JSONObject(umeng_data_str);
                    JSONObject umeng_data_data = umeng_data.getJSONObject("data");
                    String msg_id = umeng_data_data.getString("msg_id");

                    requestNetData_status(msg_id);
                    */

                    g.Save2DB(ApplicationCustom.getInstance().db, message);


                    ShowToast("发送成功");
                    clear();

                }

            }

            @Override
            public void OnFinal() {
                super.OnFinal();

                Utils.dismissLoadingDialog();
            }
        }.start_POST();


    }


    void requestNetData_status(final String task_id){
        new NetHelper(activity){

            @Override
            public String init(ArrayList<BasicNameValuePair> map) {


                // 牵扯到发送的body只能在服务端验证了；
                // Sign=MD5($http_method$url$post-body$app_master_secret);


                String url = "http://msg.umeng.com/api/status?sign=mysign";

                String appkey = g.umeng_app_key;
                String timestamp = ""+System.currentTimeMillis();
                String sign_raw = url +

                map.add( new BasicNameValuePair("sign", ""));




                return url;
            }

            @Override
            public void onComplete(String message) throws JSONException {

            }
        }.start_POST();


    }



    void clear(){
        et_bar_input.setText("");

    }


    class Adapter extends BaseAdapter{


        class ViewHolder {

            TextView tv_content ;
            TextView tv_time ;

            LinearLayout layout_text;
            LinearLayout layout_location;
            LinearLayout layout_audio;
            LinearLayout layout_video;
            LinearLayout layout_pic;

            ImageView iv_content_pic;

            int pos;
        }

        public void refreshToBottom(){

            listview.setSelection(listdata.size());
            notifyDataSetInvalidated();
            //notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return listdata.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            final TalkMessage message = listdata.get(position);

            if (convertView == null || ((ViewHolder) convertView.getTag()).pos != position) {

                holder = new ViewHolder();
                holder.pos = position;

                if(message.getType().equals("0"))
                {
                    convertView = getLayoutInflater().inflate(R.layout.layout_62_1_right, null);
                }
                else{
                    convertView = getLayoutInflater().inflate(R.layout.layout_62_1_left, null);
                }

                holder. tv_content = (TextView)convertView.findViewById(R.id.tv_content);
                holder. tv_time = (TextView)convertView.findViewById(R.id.tv_time);
                holder.layout_text = (LinearLayout)convertView.findViewById(R.id.layout_text);
                holder.layout_location = (LinearLayout)convertView.findViewById(R.id.layout_location);
                holder.layout_audio = (LinearLayout)convertView.findViewById(R.id.layout_audio);
                holder.layout_video = (LinearLayout)convertView.findViewById(R.id.layout_video);
                holder.layout_pic = (LinearLayout)convertView.findViewById(R.id.layout_pic);

                holder.iv_content_pic = (ImageView)convertView.findViewById(R.id.iv_content_pic);
                convertView.setTag(holder);

            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }




            // 显示imjo表情，动画表情
            TalkMessage.ContentEntity entity = message.getContent();
            if(entity.getText() != null){

                String content = entity.getText().getValue();

                holder.layout_text.setVisibility(View.VISIBLE);
                holder.layout_location.setVisibility(View.GONE);
                holder.layout_audio.setVisibility(View.GONE);
                holder.layout_video.setVisibility(View.GONE);
                holder.layout_pic.setVisibility(View.GONE);

                SpannableStringBuilder builder = change2ImageSpane(content);
                holder.tv_content.setText( builder );

            }
            else if(entity.getLocation() != null){

                holder.layout_text.setVisibility(View.GONE);
                holder.layout_location.setVisibility(View.VISIBLE);
                holder.layout_audio.setVisibility(View.GONE);
                holder.layout_video.setVisibility(View.GONE);
                holder.layout_pic.setVisibility(View.GONE);


                doLocation(holder, message);


            }
            else if(entity.getAudio() != null) {

                holder.layout_text.setVisibility(View.GONE);
                holder.layout_location.setVisibility(View.GONE);
                holder.layout_audio.setVisibility(View.VISIBLE);
                holder.layout_video.setVisibility(View.GONE);
                holder.layout_pic.setVisibility(View.GONE);


                doAudio(holder, message);

            }
            else if(entity.getVideo() != null) {
                holder.layout_text.setVisibility(View.GONE);
                holder.layout_location.setVisibility(View.GONE);
                holder.layout_audio.setVisibility(View.GONE);
                holder.layout_video.setVisibility(View.VISIBLE);
                holder.layout_pic.setVisibility(View.GONE);

                doVideo(holder, message);
            }
            else if(entity.getPic() != null){

                holder.layout_text.setVisibility(View.GONE);
                holder.layout_location.setVisibility(View.GONE);
                holder.layout_audio.setVisibility(View.GONE);
                holder.layout_video.setVisibility(View.GONE);
                holder.layout_pic.setVisibility(View.VISIBLE);

                doPic(holder, message);

            }


            String time_str = Utils.getTime_YYYYMMddHHmmss(message.getCreate_at());
            holder.tv_time.setText(time_str);



            return convertView;
        }


        void doLocation(ViewHolder holder, final TalkMessage talkmessage) {

            final String content = GsonParse.parse( talkmessage.getContent() );

            //ShowToast(str);
            //Double lo = obj.getDouble("lo");
            //Double la = obj.getDouble("la");

            // 显示一张地理位置图片

            holder.layout_location.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, _62_1MoreFragmentMapActivity.class);
                    intent.putExtra("data", content);
                    startActivity(intent);
                }
            });





        }

        void doAudio(ViewHolder holder, final TalkMessage talkmessage) {
            //JSONObject obj = new JSONObject(str);


    //        ShowToast(str);

            // 显示一张音频播放位图
            holder.layout_audio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String filename_local = talkmessage.getContent().getAudio().getFilename_local();
                    if(filename_local.isEmpty()){
                        requestNetData_download(v, talkmessage);

                    }
                    else{

                        //ShowToast(filename_local);

                        if(!ApplicationCustom.getInstance().audio.isPlaying())
                            ApplicationCustom.getInstance().audio.play(filename_local);
                        else{
                            ApplicationCustom.getInstance().audio.stop_play();
                        }

                    }



                }
            });



        }


        void doVideo(ViewHolder holder, final TalkMessage talkmessage) {


            //        ShowToast(str);

            // 显示一张视频播放位图
            holder.layout_video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final String filename_local = talkmessage.getContent().getVideo().getFilename_local();
                    if(filename_local.isEmpty()){
                        requestNetData_download_video(v, talkmessage);

                    }
                    else{


                        //ApplicationCustom.getInstance().video.play_system(activity, filename_local);


                        Dialog dialog = new Dialog(activity);
                        dialog.setContentView(R.layout.dialog_62_1_layout_video);
                        dialog.show();
                        //video_play_videoview(dialog, filename_local);
                        video_play_surfaceview(dialog, filename_local);

                    }



                }
            });



        }

        void doPic(ViewHolder holder, final TalkMessage talkmessage) {



            // 显示一张
            holder.layout_pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final String filename_local = talkmessage.getContent().getPic().getFilename_local();

                    if(filename_local.isEmpty()){
                        requestNetData_download_pic(v, talkmessage);

                    }
                    else{

                        Dialog dialog = new Dialog(activity);
                        dialog.setTitle("查看图片");
                        dialog.setContentView(R.layout.dialog_62_1_layout_pic);


                        ImageView iv_content = (ImageView)dialog.findViewById(R.id.iv_content);

                        Bitmap bitmap = Utils_Image.decodeFile(filename_local);
                        iv_content.setImageBitmap(bitmap);

                        dialog.show();

                    }


                }
            });


            String filename_local = talkmessage.getContent().getPic().getFilename_local();
            if(filename_local.isEmpty() == false){
                Bitmap bitmap = Utils_Image.decodeFile(filename_local);
                holder.iv_content_pic.setImageBitmap(bitmap);

            }



        }



        void video_play_videoview(Dialog dialog, final String filename_local){

            final SurfaceView surfaceview = (SurfaceView)dialog.findViewById(R.id.surfaceview);
            final VideoView videoview = (VideoView)dialog.findViewById(R.id.videoview);
            surfaceview.setVisibility(View.GONE);
            videoview.setVisibility(View.VISIBLE);

            Button btn_play = (Button)dialog.findViewById(R.id.btn_play);
            Button btn_pause = (Button)dialog.findViewById(R.id.btn_pause);
            Button btn_stop = (Button)dialog.findViewById(R.id.btn_stop);

            btn_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!ApplicationCustom.getInstance().video.isPlaying())
                        ApplicationCustom.getInstance().video.play_videoview( activity, videoview, filename_local);
                }
            });

            btn_pause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ApplicationCustom.getInstance().video.switch_pause();
                }
            });

            btn_stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ApplicationCustom.getInstance().video.stop_play();

                }
            });


        }

        void video_play_surfaceview(Dialog dialog, final String filename_local){

            final SurfaceView surfaceview = (SurfaceView)dialog.findViewById(R.id.surfaceview);
            Button btn_play = (Button)dialog.findViewById(R.id.btn_play);
            Button btn_pause = (Button)dialog.findViewById(R.id.btn_pause);
            Button btn_stop = (Button)dialog.findViewById(R.id.btn_stop);

            btn_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!ApplicationCustom.getInstance().video.isPlaying())
                        ApplicationCustom.getInstance().video.play(surfaceview, filename_local);
                }
            });

            btn_pause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ApplicationCustom.getInstance().video.switch_pause();
                }
            });

            btn_stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ApplicationCustom.getInstance().video.stop_play();

                }
            });


        }




        SpannableStringBuilder change2ImageSpane(String text){

            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            String rexgString = g.imjo_key();
            Pattern pattern = Pattern.compile(rexgString);
            Matcher matcher = pattern.matcher(text);

            // 讲上图中标示部分替换成图标
            while (matcher.find()) {
                String value = matcher.group();
                int r = g.imjo_find(value);



                builder.setSpan(
                        new ImageSpan(activity, r), matcher.start(), matcher
                                .end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            return builder;
        }



    }



    void requestNetData_download(final View view, final TalkMessage talkmessage){


        Utils.showLoadingDialog(activity, "下载中", false);

        new NetHelper_File(activity){

            @Override
            public String init(Map<String, Object> map_url, Params params) {

                return talkmessage.getContent().getAudio().getSrc();
            }

            @Override
            public void OnFailure(String statusCode, String content, Throwable error) {

            }

            @Override
            public void OnFinal(String str) {
                Utils.dismissLoadingDialog();
            }

            @Override
            public void OnSuccess( File file) {

                String content = GsonParse.parse(talkmessage);
                String content_md5 = Utils_Data.MD5(content);

                talkmessage.getContent().getAudio().setFilename_local(file.getAbsolutePath());
                ApplicationCustom.getInstance().audio.play(file.getAbsolutePath()); // 播放
                //adapter.notifyDataSetChanged();


                // 更新本地数据库
                g.update2DB(ApplicationCustom.getInstance().db, content_md5, talkmessage);

            }

            @Override
            public void OnProgress(int bytesWritten, int totalSize, float percentage) {
                super.OnProgress(bytesWritten, totalSize, percentage);


                view.setAlpha(percentage);


            }
        }.start();


    }

    void requestNetData_download_video(final View view, final TalkMessage talkmessage){


        Utils.showLoadingDialog(activity, "下载中", false);

        new NetHelper_File(activity){

            @Override
            public String init(Map<String, Object> map_url, Params params) {

                return talkmessage.getContent().getVideo().getSrc();
            }

            @Override
            public void OnFailure(String statusCode, String content, Throwable error) {

            }

            @Override
            public void OnFinal(String str) {
                Utils.dismissLoadingDialog();
            }

            @Override
            public void OnSuccess( File file) {

                String content = GsonParse.parse(talkmessage);
                String content_md5 = Utils_Data.MD5(content);

                talkmessage.getContent().getVideo().setFilename_local(file.getAbsolutePath());
        //        ApplicationCustom.getInstance().video.play(file.getAbsolutePath()); // 播放
                //adapter.notifyDataSetChanged();


                // 更新本地数据库
                g.update2DB(ApplicationCustom.getInstance().db, content_md5, talkmessage);

            }

            @Override
            public void OnProgress(int bytesWritten, int totalSize, float percentage) {
                super.OnProgress(bytesWritten, totalSize, percentage);


                view.setAlpha(percentage);


            }
        }.start();


    }


    void requestNetData_download_pic(final View view, final TalkMessage talkmessage){


        Utils.showLoadingDialog(activity, "下载中", false);

        new NetHelper_File(activity){

            @Override
            public String init(Map<String, Object> map_url, Params params) {

                return talkmessage.getContent().getPic().getSrc();
            }

            @Override
            public void OnFailure(String statusCode, String content, Throwable error) {

            }

            @Override
            public void OnFinal(String str) {
                Utils.dismissLoadingDialog();
            }

            @Override
            public void OnSuccess( File file) {

                String content = GsonParse.parse(talkmessage);
                String content_md5 = Utils_Data.MD5(content);

                talkmessage.getContent().getPic().setFilename_local(file.getAbsolutePath());
                //        ApplicationCustom.getInstance().video.play(file.getAbsolutePath()); // 播放
                adapter.notifyDataSetChanged();


                // 更新本地数据库
                g.update2DB(ApplicationCustom.getInstance().db, content_md5, talkmessage);

            }

            @Override
            public void OnProgress(int bytesWritten, int totalSize, float percentage) {
                super.OnProgress(bytesWritten, totalSize, percentage);


                view.setAlpha(percentage);


            }
        }.start();


    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mycamera.OnActivityResult(requestCode, resultCode, data);
        myphotoalbum.OnActivityResult(requestCode, resultCode, data);


    }



}
